<template>
  <div class="components-score-prod-sku-tag mod-prod-sku-tag">
    <el-form-item
      :label="$t('prodSku.prodSku')"
      :label-width="$t('language') === 'English'?'150px':'130px'"
    >
      <div class="sku-border">
        <!-- 新增的商品sku tag -->
        <div
          v-for="(tag, tagIdx) in skuTags"
          :key="tag.tagName"
          class="tagTree"
        >
          <div class="tag">
            <!-- 规格名 -->
            <div class="sku-background spec-name-box">
              <div class="spec-name">
                <div class="tag-item-tit">
                  {{ $t('prodSku.skuName') }}
                </div>
                <div>
                  <div>
                    <!-- $t('language') === 'English' ? tag.tagNameEn : -->
                    <el-select
                      :model-value="tag.tagName"
                      filterable
                      default-first-option
                      allow-create
                      :placeholder="$t('tip.select')"
                      @change="onChangeTagName($event, tagIdx)"
                    >
                      <el-option
                        v-for="item in unUseTags"
                        :key="item.propId"
                        :label="item.propName"
                        :value="item.propName"
                      />
                    </el-select>
                    <!-- 添加图片 -->
                    <span
                      v-if="tagIdx === 0"
                      class="add-img"
                    >
                      <el-checkbox
                        v-model="addImgchecked"
                        @change="onHandleAddImgchecked(tagIdx)"
                      >{{ $t('prodSku.addSpecPic') }}</el-checkbox>
                    </span>
                    <div class="del-spec-btn">
                      <el-icon @click="onRemoveTag(tagIdx)">
                        <CircleCloseFilled />
                      </el-icon>
                    </div>
                  </div>

                  <div
                    v-if="tagIdx === 0"
                    class="first-tag-tips"
                  >
                    {{ $t('prodSku.postProductTips11') }}
                  </div>
                </div>
              </div>
            </div>
            <!-- 规格值 -->
            <div
              v-if="tag.tagName"
              class="spec-val"
            >
              <div class="tag-item-tit">
                {{ $t('prodSku.skuValue') }}
              </div>
              <div class="tag-item-box">
                <div
                  class="item-list"
                  :class="{ 'ft-spec-val': tagIdx === 0 }"
                >
                  <div
                    v-for="(tagItem, tagItemIndex) in tag.tagItems"
                    :key="tagItem.valueId"
                    class="spec-val-item"
                    :class="{ 'ft-spec-val-item': tagIdx === 0 && !tagItem.creating && addImgchecked }"
                  >
                    <div class="item">
                      <div class="prop-value">
                        <div class="text-hid">
                          {{ tagItem.propValue }}
                        </div>
                        <!-- 第一个规格允许上传图片 -->
                        <div
                          v-if="tagIdx === 0 && !tagItem.creating && addImgchecked"
                          class="up-box"
                        >
                          <div class="img-upload">
                            <ImgUpload
                              :model-value="tagItem.pic"
                              @update:model-value="onChangeTagItemPic($event, tagItem, tagIdx, tagItemIndex)"
                            />
                          </div>
                          <div
                            v-if="tagItem.pic"
                            class="default-btn text-btn"
                            @click="onDelTagItemPic(tagIdx, tagItemIndex)"
                          >
                            {{ $t('text.delBtn') }}
                          </div>
                        </div>
                      </div>
                      <div
                        class="del-btn"
                        @click="onHandleTagClose(tagIdx, tagItemIndex)"
                      >
                        <el-icon>
                          <Close />
                        </el-icon>
                      </div>
                    </div>
                  </div>

                  <!-- 添加规格值 -->
                  <div class="add-item">
                    <el-select
                      v-if="tagItemInputs[tagIdx] && tagItemInputs[tagIdx].visible"
                      :ref="(el)=>{saveTagInputList[`saveTagInput${tagIdx}`]=el}"
                      v-model="tagItemInputs[tagIdx].value"
                      filterable
                      allow-create
                      default-first-option
                      value-key="valueId"

                      :placeholder="$t('tip.select')"
                      class="input-new-tag"
                      @visible-change="onAddSkuTagItem($event, tagIdx)"
                    >
                      <el-option
                        v-for="item in getTagValues(tag.tagName, tag.tagItems)"
                        :key="item.valueId"
                        :label="item.propValue"
                        :value="item"
                      />
                    </el-select>
                    <el-icon
                      :size="20"
                      class="add-btn"
                      color="#155bd4"
                      :class="{'disable': !tag.showAddTagBtn}"
                      @click="onShowTagInput(tagIdx)"
                    >
                      <CirclePlus />
                    </el-icon>
                  </div>
                  <!-- 添加规格值 / -->
                </div>
                <div
                  v-if="tagIdx === 0"
                  class="img-tips"
                >
                  {{ $t('prodSku.postProductTips12') }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 添加商品规格按钮 -->
        <div class="sku-background">
          <div
            class="default-btn add-sku-btn"
            @click="onAddskuTag()"
          >
            {{ $t("prodSku.addSpecifications") }}
          </div>
          <span
            v-if="!skuTags.length"
            class="tips"
          >{{ $t("prodSku.postProductTips13") }}</span>
          <span
            v-if="skuTags.length"
            class="tips"
          >({{ $t('shopProcess.mostAdd') + maxNumOfCombo + $t('shopProcess.group') }})</span>
        </div>
      </div>
    </el-form-item>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { validNoEmptySpace } from '@/utils/validate'
import { getUUID } from '@/utils'
import { getCurrentInstance } from 'vue'

const emit = defineEmits(['resetInit', 'change', 'clearSkuImg', 'changeSkuImg'])

const props = defineProps({
  // eslint-disable-next-line vue/require-prop-types
  skuList: {
    default: []
  }
})

// const addTagInput = reactive({
//   propName: '',
//   propNameEn: '',
//   propNameObj: null,
//   selectValues: []
// })
const type = ref(0)
const tagIndex = ref('')
let tagItemName = ''
let tagName = ''
// let tagItemNameEn = ''
// let tagNameEn = ''
let tagNameIndex = 0
const tagItemInputs = reactive([])
// sku的标记
// tags: []
// 数据库中的规格
const dbTags = ref([])
// 根据选定的规格所查询出来的规格值
// const dbTagValues = ref([])
const dbTagValuesMap = reactive({})
// const specs = ref([]) // 使用的规格
let maxValueId = 0 // 规格值id最大
let maxPropId = 0 // 规格id 最大
let initing = false

const addImgchecked = ref(true)
let propValue = []

// let changeImg = false

// 最大规格组合数量
const maxNumOfCombo = ref(100)
const masterLangInfo = reactive({ name: '', lang: 0 })

const $forceUpdate = getCurrentInstance().proxy.$forceUpdate

const prodStore = useProdStore()
const skuTags = computed({
  get () {
    return prodStore.skuTags
  },
  set (val) { prodStore.updateSkuTags(val) }
})

const defalutSku = computed(() => {
  return prodStore.defalutSku
})

// 未使用的规格, 通过计算属性计算
const unUseTags = computed(() => {
  const res = []
  for (let i = 0; i < dbTags.value.length; i++) {
    const dbTag = dbTags.value[i]
    const specIndex = skuTags.value.findIndex(tag => tag.tagName === dbTag.propName)
    if (specIndex === -1) {
      res.push(dbTag)
    }
  }
  return res
})
// 计算规格组合数量
const countSkuTagCombo = computed(() => {
  const _skuTags = skuTags.value.filter(el => el.tagItems && el.tagItems.length)
  const count = _skuTags.length ? _skuTags.map(tag => (tag.tagItems && tag.tagItems.length)).reduce((a, b) => a * b) : 0
  return count
})

watch(() => skuTags.value, (val) => {
  handlerTagLength(val)
  if (initing) {
    initing = false
    return
  }
  let _skuList = []
  if (type.value === 4) {
    // 删除规格值
    props.skuList.forEach((sku) => {
      const propertiesArray = sku.properties.split(';')
      if (propertiesArray[tagNameIndex] && tagItemName !== propertiesArray[tagNameIndex].substring(propertiesArray[tagNameIndex].indexOf(':') + 1)) {
        _skuList.push(sku)
      }
    })
  } else if (type.value === 2) {
    // 添加规格值
    const properties = tagName + ':' + tagItemName
    // var propertiesEn = tagNameEn + ':' + tagItemNameEn
    // 增加或删除规格
    let tempSkuList = []
    val.forEach(tag => {
      if (_skuList.length === 0) {
        if (tagName === tag.tagName) {
          const sku = Object.assign({}, defalutSku.value)
          sku.properties = properties // 销售属性组合字符串
          // sku.propertiesEn = propertiesEn // 销售属性组合字符串
          _skuList.push(sku)
        } else {
          tag.tagItems.forEach(tagItem => {
            const sku = Object.assign({}, defalutSku.value)
            sku.properties = `${tag.tagName}:${tagItem.propValue}` // 销售属性组合字符串
            // sku.propertiesEn = `${tag.tagNameEn}:${tagItem.propValueEn}` // 销售属性组合字符串
            _skuList.push(sku)
          })
        }
        if (val.length === 1) {
          _skuList = props.skuList.concat(_skuList)
        }
      } else {
        tempSkuList = []
        if (tagName === tag.tagName) {
          _skuList.forEach(sku => {
            if (!slidingCheckTagName(sku.properties, tagName)) {
              const newSku = Object.assign({}, sku)
              newSku.properties = `${sku.properties};${properties}`
              // newSku.propertiesEn = `${sku.propertiesEn};${propertiesEn}`
              tempSkuList.push(newSku)
            }
          })
        } else {
          tag.tagItems.forEach(tagItem => {
            _skuList.forEach(sku => {
              if (!slidingCheckTagName(sku.properties, tag.tagName)) {
                const newSku = Object.assign({}, sku)
                newSku.properties = `${sku.properties};${tag.tagName}:${tagItem.propValue}`
                // newSku.propertiesEn = `${sku.propertiesEn};${tag.tagNameEn}:${tagItem.propValueEn}`
                tempSkuList.push(newSku)
              }
            })
          })
        }
        _skuList = props.skuList.concat(tempSkuList)
      }
    })
  } else if (type.value === 5) {
    // 新增/更改/删除图片
    return
  } else {
    // 增加或删除规格
    let tempSkuList = []
    val.forEach(tag => {
      if (_skuList.length === 0) {
        tag.tagItems.forEach(tagItem => {
          const sku = Object.assign({}, defalutSku.value)
          sku.properties = `${tag.tagName}:${tagItem.propValue}` // 销售属性组合字符串
          // sku.propertiesEn = `${tag.tagNameEn}:${tagItem.propValueEn}` // 销售属性组合字符串
          if (tagItem.pic) {
            sku.pic = tagItem.pic
          }
          _skuList.push(sku)
        })
      } else {
        tempSkuList = []
        _skuList.forEach(sku => {
          tag.tagItems.forEach(tagItem => {
            const newSku = Object.assign({}, sku)
            newSku.properties = `${sku.properties};${tag.tagName}:${tagItem.propValue}`
            // newSku.propertiesEn = `${sku.propertiesEn};${tag.tagNameEn}:${tagItem.propValueEn}`
            if (tagItem.pic) {
              newSku.pic = tagItem.pic
            }
            tempSkuList.push(newSku)
          })
        })
        _skuList = tempSkuList
      }
    })
  }
  if (!_skuList.length) {
    _skuList.push(Object.assign({}, defalutSku.value))
  }
  emit('change', _skuList, val, type.value)
}, {
  deep: true
})

onMounted(() => {
  http({
    url: http.adornUrl('/sys/lang'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data) {
      const info = data
      masterLangInfo.name = info.name
      masterLangInfo.lang = info.lang
      // 获取规格信息
      http({
        url: http.adornUrl('/prod/spec/list'),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dbTags.value = data

        if (props.skuList.length) {
          emit('resetInit', props.skuList)
          init(props.skuList)
        }

        if (data) {
          maxPropId = Math.max.apply(Math, data.map(item => {
            return item.propId
          }))
          /** 兼容旧数据， 添加 tagId */
        } else {
          maxPropId = 0
        }
      })
    }
  })
})

onDeactivated(() => {
  // 离开发布商品页清理tag标签
  prodStore.removeSkuTag(-1)
})

const init = (skuList) => {
  if (!skuList || !skuList.length) {
    skuTags.value = []
    emit('change', [Object.assign({}, defalutSku.value)])
    return
  }
  initing = true
  const _skuTags = []
  let isIncludeImg = false
  for (let i = 0; i < skuList.length; i++) {
    const sku = skuList[i]
    if (!sku.properties) break
    const propertiesArray = sku.properties.split(';')
    const imgSrc = sku.pic
    isIncludeImg = (imgSrc && imgSrc !== '') || isIncludeImg
    for (const j in propertiesArray) {
      const cnProperties = [propertiesArray[j].slice(0, propertiesArray[j].indexOf(':')), propertiesArray[j].substring(propertiesArray[j].indexOf(':') + 1)]
      if (!_skuTags[j]) {
        _skuTags[j] = {
          tagName: cnProperties[0],
          tagItems: []
        }
        // tagItemInputs.push({ visible: false, value: '' })
      }
      const tagItemNameIndex = _skuTags[j].tagItems.findIndex((tagItemName) => tagItemName.propValue === cnProperties[1])
      if (tagItemNameIndex === -1) {
        const extarlInfo = +j === 0 ? { pic: imgSrc } : {}
        _skuTags[j].tagItems.push({
          propValue: cnProperties[1],
          ...extarlInfo
          // pic: imgSrc
        })
      }
    }
  }
  addImgchecked.value = isIncludeImg
  tagItemInputs.push({ visible: false, value: '' })
  skuTags.value = _skuTags
}
/**
 * 校验规格列表
 */
const vaildSkuTag = () => {
  let isValid = true
  if (countSkuTagCombo.value > maxNumOfCombo.value) {
    ElMessage.error(
      `${$t('prodSku.currentlyAdded') +
      countSkuTagCombo.value +
      $t('prodSku.productSpecCount')}，${$t('shopProcess.mostAdd') +
      maxNumOfCombo.value +
      $t('shopProcess.group')}`
    )
    // ElMessage.error(`当前已添加【${countSkuTagCombo}组】商品规格，最多可添加${maxNumOfCombo}组`)
    return false
  }
  if (skuTags.value && skuTags.value.length) {
    // eslint-disable-next-line array-callback-return
    skuTags.value.some(sku => {
      if (!sku.tagName) {
      // 规格名不能为空
        ElMessage({
          message: $t('prodSku.specNameNotNull'),
          type: 'error',
          duration: 1000
        })
        isValid = false
        // 终止遍历
        return true
      }
      if (sku.tagName && (!sku.tagItems.length || (sku.tagItems.length && sku.tagItems.find(item => !item.propValue)))) {
        // 规格值不能为空
        ElMessage({
          message: $t('prodSku.specValueCannotBeEmpty'),
          type: 'error',
          duration: 1000
        })
        isValid = false
        // 终止遍历
        return true
      }
    })
  }
  return isValid
}
defineExpose({ init, vaildSkuTag })

/**
 * 计算规格组合数量，判断是否允许新增
 */
const handlerTagLength = (val) => {
  const _skuTags = val.filter(el => el.tagItems && el.tagItems.length)
  val.forEach((tag, idx) => {
    const ln = _skuTags.length ? _skuTags.map(tag => (tag.tagItems && tag.tagItems.length)) : []
    ln[idx] = ln[idx] ? ln[idx] + 1 : ''
    const count = ln.length ? ln.reduce((a, b) => a * b) : 0
    tag.showAddTagBtn = true
    if (count > maxNumOfCombo.value) {
      tag.showAddTagBtn = false
    }
  })
}

/**
 * 从properties属性中查找是否存在名称为参数tagName的规格名
 */
const slidingCheckTagName = (properties, tagName) => {
  if (tagName === '' && (properties.indexOf(';:') !== -1)) {
    return true
  }
  if (!tagName || tagName === '' || !properties || properties === '') {
    return false
  }
  let leftIndex = 0
  for (let i = 0; i < properties.length; i++) {
    leftIndex = i
    while (i < properties.length && properties.charAt(i) !== ':' && properties.charAt(i) !== ';') {
      ++i
    }
    if (properties.charAt(i) === ';' || (i - leftIndex) !== tagName.length || i >= properties.length) {
      continue
    }
    let j = 0
    while (properties.charAt(leftIndex++) === tagName.charAt(j)) {
      if (j + 1 === tagName.length) {
        return true
      }
      ++j
    }
  }
  return false
}

const onHandleAddImgchecked = (tagIndex) => {
  if (!addImgchecked.value) {
    // 不添加规格图片时把图片属性置空
    if (skuTags.value[tagIndex] && skuTags.value[tagIndex].tagItems) {
      for (let i = 0; i < skuTags.value[tagIndex].tagItems.length; i++) {
        const newSkuTagItem = {
          ...skuTags.value[tagIndex].tagItems[i],
          pic: ''
        }
        prodStore.updateSkuTagItem({
          tagIndex, tagItemIndex: i, skuTagItem: newSkuTagItem
        })
      }
      for (let i = 0; i < props.skuList.length; i++) {
        //
        // eslint-disable-next-line vue/no-mutating-props
        props.skuList[i].pic = ''
      }
      // changeImg = true
      $forceUpdate()
      type.value = 5
      emit('change', props.skuList, skuTags.value, type.value)
      emit('clearSkuImg')
    }
  }
}
/**
 * 添加规格名
 */
const onAddskuTag = () => {
  if (skuTags.value.find(tag => !tag.tagName ||
      !tag.tagItems.length ||
        tag.tagItems.find(tagItem => !tagItem.propValue))) {
    ElMessage({
      message: $t('prodSku.completeTheAddedSpec'),
      type: 'error',
      duration: 1000
    })
    return
  }
  prodStore.addSkuTag({
    // tagId: '',
    tagName: '',
    tagNameEn: '',
    tagItems: [
      // { propId: '', propValue: '', propValueEn: '', valueId: '', creating: true }
    ]
  })
  type.value = 1
}

/**
 * 修改规格名
 */
const onChangeTagName = (selVal, index) => {
  let useTag = unUseTags.value.find(el => selVal === el.propName || selVal === el.propNameEn)
  const is = Object.prototype.toString.call(useTag) === '[object Object]'
  const reg = /[\\;\\:\\；\\：]/g
  if (!is) {
    // 纯空格校验
    if (validNoEmptySpace(selVal)) {
      ElMessage.error($t('shopProcess.inputAllSpace'))
      return
    }
    if (reg.test(selVal)) {
      ElMessage.error($t('prodSku.specName') + $t('prodSku.specialWordSymbolTips') + ':;')
      return
    }
    // 替换:;字符
    // selVal = selVal.replace(/[\\;\\:]/g, '')
    // 判断规格名是否超长
    if (selVal.length > 10) {
      ElMessage.error($t('prodSku.postProductTips11'))
      return
    }
    // 判断规格名是否重复
    if (skuTags.value.find(el => el.tagName === selVal)) {
      ElMessage.error($t('prodSku.skuName') + '\'' + selVal + '\' ' + $t('prodSku.isExistsPleaReEn'))
      return
    }
    useTag = {
      propName: selVal,
      propNameEn: selVal
    }
  }
  const oldSkuTag = skuTags.value[index]
  // $t('language') === 'English' && oldSkuTag.tagNameEn !== '' ? oldSkuTag.tagNameEn :
  const oldValue = oldSkuTag.tagName
  if (selVal !== oldValue) {
    // 规格发生变化
    type.value = 3
  }
  if (useTag && oldSkuTag) {
    const newSkuTag = {
      tagId: useTag.propId,
      tagName: useTag.propName,
      tagNameEn: useTag.propNameEn,
      tagItems: [
        // {
        //   propId: '', propValue: '', propValueEn: '', valueId: '', creating: true
        // }
      ]
    }
    prodStore.updateSkuTag({
      index, skuTag: newSkuTag
    })
    if (is) {
      getDbTagValues(useTag.propId, useTag.propName)
    }
  }
}
/**
 * 修改规格值
 */
// eslint-disable-next-line no-unused-vars
const changeTagItemName = (value, _tagIndex, tagItemIndex) => {
  tagIndex.value = _tagIndex
  let newSkuTag = {}
  const reg = /[\\;\\；]/g
  const tagItems = []
  tagName = skuTags.value[_tagIndex].tagName
  // tagNameEn = skuTags.value[_tagIndex].tagNameEn
  type.value = 3
  if (!skuTags.value[_tagIndex].tagName) {
    // 请先选择规格
    ElMessage.error($t('prodSku.selectSpecFirst'))
    propValue = ''
    return
  }
  // value === false下拉框收起
  if (!value && propValue) {
    // for (let i = 0; i < propValue.length; i++) {
    const element = propValue
    const is = Object.prototype.toString.call(element) === '[object Object]'
    if (is) {
      tagItemName = element.propValue
      // tagItemNameEn = element.propValueEn
      tagItems.push(element)
    } else {
      // 纯空格校验
      if (validNoEmptySpace(element)) {
        ElMessage.error($t('shopProcess.inputAllSpace'))
        propValue = ''
        return
      }
      if (reg.test(element)) {
        ElMessage.error($t('prodSku.specValue') + $t('prodSku.specialWordSymbolTips') + ';')
        propValue = ''
        return
      }
      // 替换:;字符
      // element = element.replace(/[\\;\\:]/g, '')
      // 规格值是否超长
      if (element.length > 20) {
        ElMessage.error($t('prodSku.specValueCharacterLength'))
        propValue = ''
        return
      }
      maxPropId = maxPropId + 1
      maxValueId = maxValueId + 1
      tagItems.push({
        propId: maxPropId,
        propValue: element,
        propValueEn: element,
        valueId: maxValueId
      })
      tagItemName = element
      // tagItemNameEn = element
    }
    // }
    const oldSkuTag = skuTags.value[_tagIndex]
    newSkuTag = {
      ...oldSkuTag,
      tagItems
    }
    prodStore.updateSkuTag({
      index: _tagIndex, skuTag: newSkuTag
    })
    propValue = ''
  }
}

// 添加规格值
const { proxy } = getCurrentInstance()
const onAddSkuTagItem = (event, _tagIndex) => {
  tagIndex.value = _tagIndex
  // eslint-disable-next-line no-useless-escape
  const reg = /[\\;\；]/g
  const itemValue = tagItemInputs[_tagIndex].value
  if (!event && itemValue) {
    let tagItem = {}
    const index = skuTags.value[_tagIndex].tagItems.length - 1
    tagName = skuTags.value[_tagIndex].tagName
    // tagNameEn = skuTags.value[_tagIndex].tagNameEn
    const is = Object.prototype.toString.call(itemValue) === '[object Object]'
    if (is) {
      tagItemName = itemValue.propValue
      // tagItemNameEn = itemValue.propValueEn
      tagItem = {
        propId: index === -1 ? 0 : skuTags.value[_tagIndex].tagItems[index].propId,
        propValue: itemValue.propValue,
        propValueEn: itemValue.propValueEn,
        valueId: itemValue.valueId
      }
    } else {
      // 纯空格校验
      if (validNoEmptySpace(itemValue)) {
        ElMessage.error($t('shopProcess.inputAllSpace'))
        tagItemInputs[_tagIndex].value = ''
        tagItemInputs[_tagIndex].visible = true
        return
      }
      if (reg.test(itemValue)) {
        ElMessage.error($t('prodSku.specValue') + $t('prodSku.specialWordSymbolTips') + ';')
        tagItemInputs[_tagIndex].value = ''
        tagItemInputs[_tagIndex].visible = true
        return
      }
      // 替换:;字符
      // itemValue = itemValue.replace(/[\\;\\:]/g, '')
      // 规格值是否超长
      if (itemValue.length > 20) {
        ElMessage.error($t('prodSku.specValueCharacterLength'))
        tagItemInputs[_tagIndex].value = ''
        tagItemInputs[_tagIndex].visible = true
        return
      }
      // 校验规格值是否重复
      if (checkTagItem(skuTags.value[_tagIndex], _tagIndex)) {
        tagItemInputs[_tagIndex].value = ''
        tagItemInputs[_tagIndex].visible = true
        return
      }
      tagItemName = itemValue
      // tagItemNameEn = itemValue
      tagItem = {
        propId: index === -1 ? 0 : skuTags.value[_tagIndex].tagItems[index].propId,
        propValue: itemValue,
        propValueEn: itemValue,
        valueId: index === -1 ? 0 : getUUID()
      }
    }
    if (tagItem) {
      prodStore.addSkuTagItem({ tagIndex: _tagIndex, tagItem })
      tagItemInputs[_tagIndex].visible = false
      tagItemInputs[_tagIndex].value = ''
      type.value = 2
    }
  }
  if (!event && !itemValue && tagItemInputs[_tagIndex].visible) {
    tagItemInputs[_tagIndex].visible = false
    tagItemInputs[_tagIndex].value = ''
    proxy.$forceUpdate()
  }
}

// 修改图片
const onChangeTagItemPic = (value, skuTagItem, tagIndex, tagItemIndex) => {
  const skuTag = skuTags.value[tagIndex]
  if (skuTag && skuTagItem) {
    const newSkuTagItem = {
      ...skuTagItem,
      pic: value
    }
    prodStore.updateSkuTagItem({
      tagIndex, tagItemIndex, skuTagItem: newSkuTagItem
    })
    // changeImg = true
    $forceUpdate()
    type.value = 5
    // 把对应的sku图片修改
    for (let i = 0; i < props.skuList.length; i++) {
      if (!props.skuList[i].properties) {
        continue
      }
      const pName = (props.skuList[i].properties.split(';'))[0]
      const properties = pName.substring(pName.indexOf(':') + 1)
      if (properties === skuTagItem.propValue) {
        // eslint-disable-next-line vue/no-mutating-props
        props.skuList[i].pic = value
      }
    }
    emit('changeSkuImg', skuTagItem.propValue, value)
  }
}
const onDelTagItemPic = (tagIndex, tagItemIndex) => {
  const skuTagItem = Object.assign({}, skuTags.value[tagIndex].tagItems[tagItemIndex])
  skuTagItem.pic = ''
  onChangeTagItemPic('', skuTagItem, tagIndex, tagItemIndex)
  // changeImg = true
  type.value = 5
}
/**
 * 获取对应规格名下的规格值列表
 */
const getTagValues = (key, usedItems) => {
  const fd = dbTags.value.find(fdItem => fdItem.propName === key)
  if (fd) {
    const result = fd.prodPropValues.map(item => {
    // 默认显示主语言的信息
      const master = item.prodPropValueLangList.find(m => m.lang === masterLangInfo.lang)
      item.propValue = master ? master.propValue : item.prodPropValueLangList[0].propValue
      return item
    })

    // 过滤出未被选择的规格值
    const propValues = usedItems.map(el => el.propValue)
    const filterList = result.filter(item => !propValues.includes(item.propValue))
    return filterList
  } else {
    return []
  }
}
/**
 * 获取listSpecValue并设置到dbTagValuesMap
 */
const getDbTagValues = (propId, tagName) => {
  if (dbTagValuesMap[tagName]) return
  http({
    url: http.adornUrl(`/prod/spec/listSpecValue/${propId}`),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    dbTagValuesMap[tagName] = data
    $forceUpdate()
  })
}
// 关闭标签 --删除
const onHandleTagClose = (tagIndex, tagItemIndex) => {
  tagName = skuTags.value[tagIndex].tagName
  // tagNameEn = skuTags.value[tagIndex].tagNameEn
  tagNameIndex = tagIndex
  tagItemName = skuTags.value[tagIndex].tagItems[tagItemIndex].propValue
  // tagItemNameEn = skuTags.value[tagIndex].tagItems[tagItemIndex].propValueEn
  // if (skuTags.value[tagIndex].tagItems.length === 1) {
  //   return
  // }
  type.value = 4
  prodStore.removeSkuTagItem({ tagIndex, tagItemIndex })
}

const saveTagInputList = ref({})
// 显示标签输入框
const onShowTagInput = (tagIndex) => {
  // 判断是否允许添加
  if (!skuTags.value[tagIndex].showAddTagBtn) {
    ElMessage.error(
      `${$t('prodSku.currentlyAdded') +
      countSkuTagCombo.value +
      $t('prodSku.productSpecCount')}（${$t('shopProcess.mostAdd') +
      maxNumOfCombo.value +
      $t('shopProcess.group')}），${$t('prodSku.cannotAddUnderThisSpec')}`
    )
    // ElMessage.error(`当前已添加${countSkuTagCombo}组商品规格（${$t('shopProcess.mostAdd')}${maxNumOfCombo.value}组），该规格名下不可添加`)
    return
  }
  tagItemInputs.push({ visible: false, value: '' })
  tagItemInputs[tagIndex] = { visible: true, value: '' }
  const useTag = dbTags.value.find(el => el.propName === skuTags.value[tagIndex].tagName)
  const is = Object.prototype.toString.call(useTag) === '[object Object]'
  if (is) {
    getDbTagValues(useTag.propId, useTag.propName)
  }
  nextTick(() => {
    saveTagInputList.value[`saveTagInput${tagIndex}`].value?.focus()
  })
}
// 删除 规格
const onRemoveTag = (tagIndex) => {
  type.value = 3
  prodStore.removeSkuTag(tagIndex)
}
/**
 * 新增规格值时，判断是否存在同名的规格值
 */
const checkTagItem = (tag, tagIndex) => {
  const tagItem = tagItemInputs[tagIndex].value
  if (!tagItem) {
    tagItemInputs[tagIndex].visible = false
    tagItemInputs[tagIndex].value = ''
    return true
  }
  let isSame = false
  // skuTags.value.forEach(tag => {
  const arr = tag.tagItems.map((item) => {
    return $t('language') === 'English' ? item.propValueEn : item.propValue
  })
  if (arr.indexOf(tagItem) !== -1) {
    isSame = true
    ElMessage.error($t('prodSku.skuValue') + '\'' + tagItem + '\' ' + $t('prodSku.isExistsPleaReEn'))
    // return false
  }
  // })
  return isSame
}
</script>

<style lang="scss" scoped>
.components-score-prod-sku-tag{
  &.mod-prod-sku-tag {
    // eslint-disable-next-line vue-scoped-css/no-unused-selector
    .el-tag + .el-tag {
      margin-left: 10px;
    }
    .input-new-tag {
      width: 150px;
      margin-bottom: 10px;
      // margin-left: 10px;
      // vertical-align: bottom;
    }
    .text-btn {
      display: inline-block;
      margin-left: 5px;
    }
  }

  &.mod-prod-sku-tag {
    & :deep(img) {
      vertical-align: top;
    }
    // 新增规格外部边框
    .sku-border{
      border: 1px solid #DCDCDC;
      width: 100%;
      box-sizing: border-box;
      // padding-bottom: 10px;
      // width:70%
    }
    & :deep( .sku-background){
      background-color: #f8f8f8;
      margin: 10px;
      padding: 7px 10px;
      .el-button{
        margin-left: 10px;
        span{
          color:#000 !important;
        }
      }
      .el-form-item__label{
        padding:0 24px 0 0
      }
      .add-sku-btn {
        height: 28px;
        line-height: 28px;
        // margin-left: 10px;
      }
      .tips {
        font-size: 12px;
        color: #999999;
        margin-left: 10px;
      }
    }
    .tag-item-tit {
      min-width: 45px;
      margin-right: 10px;
    }
    // 规格名
    .sku-background.spec-name-box {
      .spec-name {
        display: flex;
        position: relative;
        .first-tag-tips {
          color: #999;
          font-size: 12px;
          height: 1em;
          line-height: 1em;
          margin: 5px 0;
        }
      }

      & :deep(.el-input__inner) {
        width: 150px;
      }
      .del-spec-btn {
        display: inline-block;
        font-size: 20px;
        // line-height: 47px;
        position: absolute;
        right: 10px;
        top: 0;
        bottom: 0;
        vertical-align: middle;
        color: #BFBFBF;
        cursor: pointer;
        & :deep(.el-icon-error) {
          vertical-align: middle;
        }
      }
      .add-img {
        margin-left: 10px;
      }
    }
    // 规格值
    .spec-val {
      display: flex;
      margin: 0 10px;
      padding: 0 10px;
      .tag-item-tit {
        margin-right: 12px;
      }
      .spec-val-item {
        margin-bottom: 10px;
        & :deep(.el-input__inner) {
          width: 100%;
          padding-left: 0!important;
          padding-right: 5px;
          border: 0;
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
        }
        & :deep(.el-input__suffix) {
          display: none;
        }
        position: relative;
        display: inline-block;
        width: 150px;
        line-height: 1.5em;
        padding: 0 10px;
        box-sizing: border-box;
        border: 1px solid #DCDCDC;
        .item {
          display: flex;
          justify-content: space-between;
          .prop-value {
            width: 90%;
            .text-hid {
              display: block;
              width: 100%;
              height: 32px;
              line-height: 32px;
              overflow: hidden;
              text-overflow:ellipsis;
              white-space: nowrap;
            }
            .up-box {
              display: flex;
              align-items: flex-end;
              .img-upload {
                & :deep(.plugin-images),
                & :deep(.plugin-images .el-upload--picture-card),
                & :deep(.el-upload-list),
                & :deep(.el-upload-list__item.is-success) {
                  width: 80px;
                  height: 80px;
                  line-height: 80px;
                  border-radius: 0;
                }
                & :deep(.plugin-images) .el-upload--picture-card {
                  border: 1px dashed #155BD4;
                  background: transparent;
                  & i {
                    font-size: 18px;
                    font-weight: bold;
                    color: #155BD4;
                  }
                }
              }
              .text-btn {
                height: 20px;
                line-height: 20px;
              }
            }
          }
          .del-btn {
            font-size: 12px;
            line-height: 32px;
            color: #999;
            cursor: pointer;
          }
        }
        // &:not(:last-child) {
        //   margin-right: 5px;
        // }
      }
      .spec-val-item:not(:last-child) {
        margin-right: 10px;
      }
      .add-btn {
        font-size: 20px;
        line-height: 32px;
        vertical-align: middle;
        color: #155bd4;
        cursor: pointer;
      }
      .add-btn.disable {
        color: #DCDCDC;
      }

      // 第一个规格值
      .spec-val-item.ft-spec-val-item {
        padding: 0px 10px 10px 10px;
        & :deep(.el-input__inner) {
          padding-left: 5px;
          padding-right: 5px;
          border: 0;
          height: 24px;
          line-height: 24px;
          margin-bottom: 5px;
        }
        .item {
          .del-btn {
            display: block;
            font-size: 12px;
            line-height: 28px;
            color: #999;
            cursor: pointer;
          }
        }
      }
      .tag-item-box {
        .item-list {
          display: flex;
          align-items: flex-start;
          flex-wrap: wrap;
        }
        .img-tips {
          height: 1em;
          line-height: 1em;
          margin-bottom: 10px;
          color: #999999;
          font-size: 12px;
        }
      }
    }

    .ft-spec-val {
      .add-btn {
        vertical-align: top;
      }
    }
    .tagTree{
      .tag {
        margin: 0
      }
    //   margin-left: 18px;
    //   margin-bottom: 8px;
    }
  }
}
</style>
